library flutter_chat_bubble;

import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/extension/date_string_extension.dart';
import 'package:tiktokadult/hj_page/mine_business/chat/widget/chat_logic.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

import '../../../../../../tools_base/widget/header_widget.dart';
import '../../../../hj_model/message/message_bean.dart';
import '../../../../tools_base/widget/net_image_widget.dart';
import 'bubble_type.dart';
import 'chat_msg_type.dart';
import 'clippers/chat_bubble_clipper_5.dart';

/// Bottom Fixed Filed
class BottomInputField extends GetView<ChatLogic> {
  const BottomInputField({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      bottom: true,
      child: Container(
        color: Color(0xff000000),
        child: Container(
          height: 58,
          width: Get.width,
          margin: EdgeInsets.symmetric(vertical: 12.h, horizontal: 18.w),
          child: Row(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(color: Color(0x1AFFFFFF), borderRadius: BorderRadius.circular(90)),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    cursorColor: AppColors.primaryXColor,
                    maxLines: 100,
                    minLines: 1,
                    focusNode: controller.focusNode,
                    onChanged: controller.onFieldChanged,
                    controller: controller.textEditingController,
                    style: TextStyle(color: Colors.white, fontSize: 14.sp),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "私信需要消费${Config.sendMsgPrice == -1 ? 0 : Config.sendMsgPrice}金币",
                      hintStyle: const TextStyle(color: Color(0xFF525252), fontSize: 12, fontWeight: FontWeight.w400),
                      contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                      isDense: true,
                    ),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 12),
                child: GestureDetector(
                  onTap: () {
                    controller.showBottomSheet(context);
                  },
                  child: Container(
                    child: SizedBox(
                      height: 24,
                      width: 24,
                      child: Image.asset(
                        "icon_pic.webp".commentPath,
                      ),
                    ),
                  ),
                ),
              ),
              10.sizeBoxW,
              GestureDetector(
                onTap: () {
                  controller.onFieldSubmitted();
                },
                child: Container(
                  child: Image.asset(
                    "ic_send.webp".commentPath,
                    width: 28,
                    height: 28,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Bubble extends StatelessWidget {
  final EdgeInsetsGeometry? margin;
  final MessageBean chat;
  Bubble({
    super.key,
    this.margin,
    required this.chat,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          chat.createdAt?.utcTimeSToMDHMString(gap: ".") ?? "",
          style: TextStyle(color: Color(0xFF989898), fontSize: 12.sp, height: 1),
        ),
        12.h.sizeBoxH,
        Row(
          mainAxisAlignment: alignmentOnType,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (chat.type == ChatMessageType.received)
              HeaderWidget(
                headPath: chat.sendAvatar ?? "",
                headWidth: 40,
                headHeight: 40,
                level: 0,
                borderHeight: 0,
                isCircle: true,
                defaultHead: Container(
                  color: Colors.grey,
                ),
              ),
            12.horizontalSpace,
            if (chat.content != null && chat.content!.isNotEmpty)
              Container(
                child: PhysicalShape(
                  clipper: clipperOnType,
                  elevation: 2,
                  color: bgColorOnType,
                  child: Container(
                    constraints: BoxConstraints(
                      maxWidth: MediaQuery.of(context).size.width * 0.6,
                    ),
                    padding: paddingOnType,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          (chat.content ?? ""),
                          style: TextStyle(
                            color: textColorOnType,
                            fontSize: 16.sp,
                          ),
                          overflow: TextOverflow.visible,
                          softWrap: true,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            if (chat.imgUrl != null && chat.imgUrl!.isNotEmpty)
              GestureDetector(
                  onTap: () => _showDialog(context, chat.imgUrl?[0]),
                  child: Container(
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                      ),
                      constraints: BoxConstraints(maxHeight: 0.25.sh, maxWidth: 0.6.sw),
                      margin: const EdgeInsets.only(top: 20),
                      child: NetworkImageLoader(
                        imageUrl: chat.imgUrl?[0] ?? "",
                        borderRadius: 8,
                      ))),
            12.horizontalSpace,
            if (chat.type == ChatMessageType.sent)
              HeaderWidget(
                headPath: chat.sendAvatar ?? "",
                headWidth: 40,
                headHeight: 40,
                level: 0,
                borderHeight: 0,
                defaultHead: Container(
                  color: Colors.grey,
                ),
              ),
          ],
        ),
      ],
    );
  }

  Color get textColorOnType {
    switch (chat.type) {
      case ChatMessageType.sent:
        return Color(0xFF000000);
      case ChatMessageType.received:
        return Color(0xFFFFFFFF);
    }
  }

  Color get bgColorOnType {
    switch (chat.type) {
      case ChatMessageType.received:
        return Color(0x0DFFFFFF);
      case ChatMessageType.sent:
        return Color(0xFF1DC194);
    }
  }

  CustomClipper<Path> get clipperOnType {
    switch (chat.type) {
      case ChatMessageType.sent:
        return ChatBubbleClipper5(type: BubbleType.sendBubble, radius: 12);
      case ChatMessageType.received:
        return ChatBubbleClipper5(type: BubbleType.receiverBubble, radius: 12);
    }
  }

  CrossAxisAlignment get crossAlignmentOnType {
    switch (chat.type) {
      case ChatMessageType.sent:
        return CrossAxisAlignment.end;
      case ChatMessageType.received:
        return CrossAxisAlignment.start;
    }
  }

  MainAxisAlignment get alignmentOnType {
    switch (chat.type) {
      case ChatMessageType.received:
        return MainAxisAlignment.start;

      case ChatMessageType.sent:
        return MainAxisAlignment.end;
    }
  }

  EdgeInsets get paddingOnType {
    switch (chat.type) {
      case ChatMessageType.sent:
        return const EdgeInsets.all(12);
      case ChatMessageType.received:
        return const EdgeInsets.symmetric(horizontal: 12, vertical: 18);
    }
  }

  //图像放大
  _showDialog(BuildContext context, String? url) async {
    if (url == null) return;
    await showDialog(
        context: context,
        builder: (ctx) {
          return SafeArea(
              child: GestureDetector(
            onTap: () {
              Navigator.of(context).pop();
            },
            onLongPress: () {
              _showModalBottomSheet(context, url);
            },
            child: Center(
                child: NetworkImageLoader(
              imageUrl: url,
            )),
          ));
        });
  }

  //底部弹出框
  _showModalBottomSheet(BuildContext context, String url) {
    final List<String> textList = ['保存图片', '取消'];
    showModalBottomSheet(
        isScrollControlled: true,
        context: context,
        builder: (context) => SafeArea(
              child: SizedBox(
                height: 120,
                child: ListView(
                    children: List.generate(
                  textList.length,
                  (index) => InkWell(
                    child: Container(alignment: Alignment.center, height: 60.0, child: Text('${textList[index]}')),
                    onTap: () {
                      if (index == 0) {
                        // ImagePickers.saveImageToGallery(url);
                        savePicture(url);
                      }
                      Navigator.pop(context);
                    },
                    onLongPress: () {
                      _showModalBottomSheet(context, url);
                    },
                  ),
                )),
              ),
            ));
  }

  void savePicture(String url) async {
    print('=========url========$url');
    var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
    await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    print('图片保存成功');
  }
}
